<template>
  <div class="temple">
    <div style="display: flex; flex-direction: column">
      <div style="font-weight: bold; width: 100%; flex-grow: 1">
        <el-tabs
          v-model="activeName"
          @tab-click="handleTabs"
        >
          <el-tab-pane
            label="权限设置"
            name="first"
          >
            <el-row>
              <el-col
                :span="24"
                class="left-list"
              >
                <el-container>
                  <el-header class="flex-between">
                    <el-row class="flex">
                      <div class="function-btn">
                        <el-button
                          type="primary"
                          size="small"
                          @click="handleCreateRole"
                        ><i class="el-icon-plus" />新增角色</el-button>

                      </div>
                    </el-row>
                    <el-row class="flex flex-between">
                      <el-col :offset="1">
                        <el-input
                          v-model="Role.searchKey"
                          placeholder="请输入角色名称搜索"
                          class="filter-item"
                          @keyup.enter.native="handleRoleFilter"
                        >
                          <el-button
                            slot="append"
                            icon="el-icon-search"
                            @click="handleRoleFilter"
                          />
                        </el-input>
                      </el-col>
                    </el-row>
                  </el-header>
                  <el-main>
                    <el-table
                      :data="roleData"
                      border
                      stripe
                      style="width: 100%"
                    >
                      <el-table-column
                        label="序号"
                        type="index"
                        :index="1"
                        width="70px"
                        align="center"
                      />
                      <el-table-column
                        prop="RightGroupName"
                        label="角色名称"
                        column-key
                      />
                      <el-table-column
                        prop="Memo"
                        label="角色描述"
                      />
                      <el-table-column label="拥有该角色的人员">
                        <template slot-scope="{row}">
                          <el-tag
                            v-for="item in row.Users"
                            :key="item.Id"
                            style="margin-right:5px;"
                          >{{ item.Name }}</el-tag>
                        </template>
                      </el-table-column>
                      <el-table-column
                        fixed="right"
                        label="操作"
                      >
                        <template slot-scope="scope">
                          <el-button
                            v-if="scope.row.Code=='custom'"
                            type="text"
                            size="small"
                            @click="handleEditRole(scope.row)"
                          >编辑</el-button>
                          <el-button
                            v-if="scope.row.Code=='custom'"
                            type="text"
                            size="small"
                            @click="handleDeleteRole(scope.row)"
                          >删除</el-button>
                          <el-button
                            v-if="scope.row.Code=='custom'"
                            type="text"
                            size="small"
                            @click="handlePermission(scope.row)"
                          >分配权限</el-button>
                        </template>
                      </el-table-column>
                      <template slot="empty">
                        <HelpTips :page-name="'functionGroup'" />
                      </template>
                    </el-table>
                  </el-main>
                </el-container>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane
            label="人员权限列表"
            name="second"
          >
            <el-container>
              <el-aside class="left-list">
                <el-container>
                  <el-header>人员列表</el-header>
                  <el-main>
                    <el-input
                      v-model="queryPermissionPerson.searchKey"
                      placeholder="请输入人员姓名搜索"
                      class="m margin-bottom"
                      @keyup.enter.native="handlePersonFilter"
                    >
                      <el-button
                        slot="append"
                        icon="el-icon-search"
                        @click="handlePersonFilter"
                      />
                    </el-input>
                    <div class="my-list">
                      <el-card
                        v-for="pd in personData"
                        :key="pd.Id"
                        class="box-card"
                        shadow="hover"
                        style="background: #fafafa"
                      >
                        <div
                          class="flex space-between padding-tb padding-lr-sm"
                          :class="pd.Id == currId ? 'bg-active-light' : ' '"
                          style="cursor:pointer"
                          @click="choosePerson(pd.Id, pd.Name)"
                        >
                          <div>
                            <i class="el-icon-caret-right" />{{ pd.Name }}
                          </div>
                          <div><i class="el-icon-arrow-right" /></div>
                        </div>
                      </el-card>
                    </div>
                  </el-main>
                </el-container>
              </el-aside>
              <el-main class="bg-white">
                <el-row class=" bg-white">
                  <el-header>人员权限</el-header>
                  <el-form
                    ref="personDataFormRef"
                    :model="personDataRight"
                    label-width="120px"
                    style="width: 100%"
                    class="padding-lr-sm"
                  >

                    <el-form-item label="人员姓名">
                      <div>{{ personDataRight.personName }}</div>
                    </el-form-item>
                    <el-form-item label="当前拥有角色">
                      <el-tag>{{ personDataRight.groupNames }}</el-tag>
                    </el-form-item>
                    <el-form-item label="可操作模块">
                      <template>
                        <el-tag
                          type="info"
                          style="width:100%"
                        >
                          <div class="my-list table-tree ">
                            <el-tree
                              ref="usermenutree"
                              :default-expand-all="true"
                              :default-checked-keys="personDataRight.menuIdsData"
                              :data="disableMenuData"
                              :check-strictly="true"
                              show-checkbox
                              :check-on-click-node="true"
                              :expand-on-click-node="false"
                              node-key="Id"
                              :props="menuProps"
                            />
                          </div>
                        </el-tag>
                      </template>
                    </el-form-item>
                  </el-form>
                </el-row>
              </el-main>
            </el-container>
          </el-tab-pane>
          <el-tab-pane
            label="模块权限列表"
            name="third"
          >
            <el-container>
              <el-aside class="left-list">
                <el-container>
                  <el-header>
                    系统模块列表
                  </el-header>
                  <el-main>
                    <template>
                      <div
                        class="my-list table-tree"
                        style="height:100%;overflow-y: scroll;"
                      >
                        <el-tree
                          ref="menuRighttree"
                          :default-expand-all="true"
                          :data="menuData"
                          node-key="Id"
                          :props="menuProps"
                          :highlight-current="true"
                          :expand-on-click-node="false"
                          @node-click="menuRightTreeClick"
                        />
                      </div>
                    </template>
                  </el-main>
                </el-container>
              </el-aside>
              <el-main class="bg-white">
                <el-header class="flex">
                  <div>拥有角色：<el-tag>{{ menuDataRight.groupNames }}</el-tag>
                  </div>
                </el-header>
                <el-main>
                  <el-table
                    :data="menuDataRight.userDepartData"
                    border
                    stripe
                    style="width: 100%"
                  >
                    <el-table-column
                      prop="UserName"
                      label="人员姓名"
                    />
                    <el-table-column
                      prop="DepartmentNames"
                      label="部门"
                    />
                    <template slot="empty">
                      <HelpTips :page-name="'modulePermissions'" />
                    </template>
                  </el-table>
                </el-main>
              </el-main>
            </el-container>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!-- 分配权限 -->
    <el-drawer
      :visible.sync="drawerPermission"
      :direction="direction"
      size="40%"
      :destroy-on-close="true"
      :with-header="false"
      :wrapper-closable="false"
    >
      <el-form
        ref="formPermission"
        :model="formPermission"
        label-width="100px"
        label-position="top"
      >
        <el-container style="background: #fff;height:100vh">
          <el-header style="font-weight:bold">{{ formPermission.Name }}授权 </el-header>
          <el-main>
            <div class="padding-tb bold">需要设置的人员:</div>
            <el-tag
              type="info"
              class="flex-start"
              style="width:100%"
            >
              <div
                v-for="item in checkedUsers"
                :key="item.Id"
                class="text-center black light text-normal "
              >
                <div
                  class="avater bg-grey"
                  style="position:relative"
                  @click="tagDel(item)"
                >
                  <i class="el-icon-user-solid text-xxxl padding-top-sm white" />
                  <i
                    class="el-icon-error"
                    style="position:absolute;top:0;color:#aaa"
                  />
                </div>
                {{ item.Name }}

              </div>

              <div
                class="text-center  text-normal gray"
                @click="showSelectPersonDialog"
              >
                <div class="avater bg-blue">
                  <i class="el-icon-plus text-xxxl padding-top-sm" />
                </div>
                选择人员
              </div>
            </el-tag>
            <div class="padding-tb bold">可操作模块:</div>
            <el-tag
              type="info"
              style="width:100%"
            >
              <template>
                <div class="my-list table-tree">
                  <el-tree
                    ref="menutree222"
                    :default-expand-all="true"
                    :default-checked-keys="checkedMenuData"
                    :data="disableMenuData"
                    :check-strictly="true"
                    show-checkbox
                    :expand-on-click-node="false"
                    :check-on-click-node="true"
                    node-key="Id"
                    :props="menuProps"
                  />
                </div>
              </template>
            </el-tag>
          </el-main>
          <el-footer>
            <div>
              <el-button
                size="medium"
                @click="closeDrawerPermission"
              >返回</el-button>
              <el-button
                type="primary"
                size="medium"
                @click="editPermission()"
              >保存</el-button>
            </div>
          </el-footer>
        </el-container>
      </el-form>
    </el-drawer>
    <!-- 新增角色 -->
    <el-drawer
      :visible.sync="drawerRole"
      :direction="direction"
      size="40%"
      :destroy-on-close="true"
      :with-header="false"
      :wrapper-closable="false"
    >
      <el-container style="background: #fff">
        <el-header>编辑角色 </el-header>
        <el-main>
          <el-form
            ref="roleTemp"
            :model="roleTemp"
            :rules="roleTempRules"
            label-width="100px"
          >
            <div>
              <el-form-item
                label="角色名称"
                prop="RightGroupName"
              >
                <el-input
                  v-model="roleTemp.Name"
                  type="input"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
              <el-form-item label="是否用于流程" prop="IsInFlow" class="child">
                <el-switch v-model="temp.IsInFlow" :active-value="true" :inactive-value="false" />
              </el-form-item>
              <el-form-item label="角色描述">
                <el-input
                  v-model="roleTemp.Remark"
                  type="textarea"
                  maxlength="100"
                  show-word-limit
                  rows="2"
                />
              </el-form-item>
              <el-form-item label="可操作模块">
                <template>
                  <el-tag
                    type="info"
                    style="width:100%"
                  >
                    <div class="my-list table-tree">
                      <el-tree
                        ref="menutree"
                        :default-expand-all="true"
                        :default-checked-keys="checkedMenuData"
                        :data="menuData"
                        :check-strictly="false"
                        show-checkbox
                        :check-on-click-node="true"
                        :expand-on-click-node="false"
                        node-key="Id"
                        :props="menuProps"
                      />
                    </div>
                  </el-tag>
                </template>
              </el-form-item>
            </div>
          </el-form>
        </el-main>
        <el-footer>
          <div>
            <el-button
              size="medium"
              @click="closeDrawerRole"
            >返回</el-button>
            <el-button
              type="primary"
              size="medium"
              @click="
                drawerRoletype === 'create'
                  ? createRole()
                  : editRole()
              "
            >保存</el-button>
          </div>
        </el-footer>
      </el-container>
    </el-drawer>
    <selectPerson
      ref="selectpersondialog"
      :echo-list="checkedUsers"
      @allSelect="allSelect"
    />
  </div>
</template>

<script>
import selectPerson from '@/views/components/permissions/selectperson'
import HelpTips from '@/views/components/common/helptips/help'
import {
  GetRole,
  deleteRole,
  addRole,
  editRole,
  loadRoleUser,
  saveRoleUser,
  GetMenuIdsByRoleId
} from '@/api/sysrole/sysrole'
import { GetUnitMenus } from '@/api/permission/menus'
export default {
  components: { selectPerson, HelpTips },
  data() {
    return {
      direction: 'rtl', // 抽屉方向
      activeName: 'first', // 选中状态
      roleTemp: {
        Id: '',
        Name: '',
        IsInFlow: true,
        Status: 1,
        Remark: ''
      },
      roleData: [], // 角色列表
      drawerRole: false,
      // 查询角色
      queryRole: {
        searchKey: ''
      },
      // 角色维护界面打开状态值
      drawerRoletype: '',
      roleTempRules: {
        Name: [
          { required: true, message: '角色名称必填', trigger: 'blur' },
          { max: 50, message: '角色名称不能超过50个字', trigger: 'blur' }
        ]
      },
      menuData: [],
      checkedMenuData: [], // 选择的菜单数据
      disableMenuData: [], // 在分配权限时需要禁用菜单
      menuProps: {
        value: 'Id',
        children: 'Children',
        label: 'Name'
      },
      formPermission: {
        Id: '',
        Name: ''
      },
      drawerPermission: false,
      checkedUsers: [], // 角色授权的用户
      // 查询角色人员列表参数对象
      queryPermissionPerson: {
        searchKey: ''
      },
      personData: [], // 角色分配了用户的人员列表
      // 某一人员权限展示对象
      personDataRight: {
        personName: '',
        groupNames: '', // 多个以逗号隔开
        menuIdsData: [] // 权限
      },
      // 某一人员权限展示对象
      menuDataRight: {
        groupNames: '', // 多个以逗号隔开
        userDepartData: [] // 权限
      },
      currId: ''
    }
  },
  created() {
    this.getRole()
    this.getUnitMenus()
  },
  methods: {
    // 点击tabs
    handleTabs(val) {
      if (val.name === 'first') {
        this.getRole()
      }
      if (val.name === 'second') {
        this.disableMenuData = []
        this.personDataRight = {
          personName: '',
          groupNames: '', // 多个以逗号隔开
          menuIdsData: [] // 权限
        }
        this.getUnitMenus()
        this.getPermissionPersonList()
      }
      if (val.name === 'third') {
        this.getUnitMenus()
      }
    },
    // 单位菜单
    getUnitMenus() {
      GetUnitMenus().then(res => {
        this.menuData = res.Data
        var tempArr = res.Data
        var tempArrNew = []
        if (tempArr != null && tempArr.length > 0) {
          tempArr.forEach(function(item) {
            item.disabled = true
            if (item.children.length > 0) {
              item.children.forEach(function(childrenItem) {
                childrenItem.disabled = true
              })
            }
            tempArrNew.push(item)
          })
        }
        console.log('tempArr', tempArr)
        console.log('tempArrNew', tempArrNew)
        this.disableMenuData = tempArrNew
      })
    },
    // 获取当前单位角色
    getRole() {
      GetRole(this.Role).then(res => {
        this.roleData = res.Data
      })
    },
    // 获取某角色菜单
    getRoleMenus(id) {
      GetMenuIdsByRoleId(id).then(res2 => {
        var checkIds = []
        this.menuData.forEach(item => {
          item.children.forEach(citem => {
            res2.Data.forEach(cdata => {
              if (citem.Id === cdata) {
                checkIds.push(cdata)
              }
            })
          })
        })
        this.checkedMenuData = checkIds
      })
    },
    // 通过角色名称过滤
    handleRoleFilter() {
      this.getRole()
    },
    // 打开新增角色弹窗
    handleCreateRole() {
      this.resetFormRole()
      this.drawerRoletype = 'create'
      this.drawerRole = true
      this.$nextTick(() => {
        this.$refs['roleTemp'].clearValidate()
      })
    },
    // 打开编辑角色弹窗
    handleEditRole(row) {
      this.roleTemp = Object.assign({}, row) // copy ob
      this.drawerRoletype = 'edit'
      this.drawerRole = true
      this.$nextTick(() => {
        this.$refs['roleTemp'].clearValidate()
      })
      this.getRoleMenus(row.Id)
    },
    // 新增角色
    createRole() {
      this.$refs['roleTemp'].validate(valid => {
        if (valid) {
          var ids = this.$refs.menutree.getCheckedKeys()
          var halfids = this.$refs.menutree.getHalfCheckedKeys()
          ids = ids.concat(halfids)
          // var data = {
          //   Name: this.roleTemp.Name,
          //   Remark: this.roleTemp.Remark,
          //   CheckedMenus: ids
          // }
          this.roleTemp.CheckedMenus = ids
          console.log('this.roleTemp', this.roleTemp)
          addRole(this.roleTemp).then(res => {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.drawerRole = false
            this.checkedMenuData = []
            this.getRole()
          })
        }
      })
    },
    // 编辑角色
    editRole() {
      this.$refs['roleTemp'].validate(valid => {
        if (valid) {
          var ids = this.$refs.menutree.getCheckedKeys()
          var halfids = this.$refs.menutree.getHalfCheckedKeys()
          ids = ids.concat(halfids)
          // var data = {
          //   Id: this.roleTemp.Id,
          //   Name: this.roleTemp.Name,
          //   Remark: this.roleTemp.Remark,
          //   CheckedMenus: ids
          // }
          this.roleTemp.CheckedMenus = ids
          editRole(this.roleTemp).then(res => {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.drawerRole = false
            this.checkedMenuData = []
            this.getRole()
          })
        }
      })
    },
    // 新增角色抽屉数据初始化
    resetRoleTemp() {
      this.roleTemp = {
        Id: '',
        Name: '',
        IsInFlow: true,
        Remark: ''
      }
    },
    // 删除角色
    handleDeleteRole(val) {
      this.$confirm('确认是否删除该数据?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole(val.Id).then(res => {
          this.$message({
            message: res.Msg,
            type: 'success',
            duration: 5 * 1000
          })
          this.getRole()
        })
      })
    },
    // 关闭新增角色弹窗
    closeDrawerRole() {
      this.$refs.menutree.setCheckedKeys([])
      this.drawerRole = false
    },

    // 为角色分配权限，即分配人员
    handlePermission(row) {
      this.formPermission = Object.assign({}, row) // copy ob
      this.getRoleUser()
      this.getRoleMenus(row.Id)
      this.drawerPermission = true
    },
    getRoleUser() {
      var paras = { Id: this.formPermission.Id }
      loadRoleUser(paras).then(res => {
        this.checkedUsers = res.Data
      })
    },
    editPermission() {
      var data = {
        RoleId: this.formPermission.Id,
        UserIds: this.checkedUsers
      }
      saveRoleUser(data)
        .then(res => {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.getRole()
          this.resetPermission()
        })
        .catch(res => {
          this.resetPermission()
        })
    },
    resetPermission() {
      this.formPermission = {
        Id: '',
        Name: ''
      }
      this.checkedUsers = []
      this.drawerPermission = false
    },
    closeDrawerPermission() {
      this.resetPermission()
    },
    tagDel(obj) {
      this.checkedUsers.splice(this.checkedUsers.indexOf(obj), 1)
    },
    showSelectPersonDialog() {
      this.$refs.selectpersondialog.showSelectPersonDialog()
    },
    // 回调方法
    allSelect(taglist) {
      this.checkedUsers = taglist
    },
    // 输入人员姓名进行搜索
    handlePersonFilter() {
      this.getPermissionPersonList()
    }

  }
}
</script>

<style lang="scss" scoped>
.el-container {
  height: calc(100vh - 150px);
}
.el-drawer__body > .el-container {
  height: calc(100vh - 20px);
}
.el-table .warning-row {
  background: oldlace;
}
.el-table .success-row {
  background: #f0f9eb;
}
.right-set {
  height: calc(100vh - 335px);
  overflow-y: scroll;
  box-shadow: 0 0 5px #aaa;
  border-radius: 4px;
  margin: 0 10px;
  padding: 10px;
}

::v-deep.el-drawer__body .el-tree-node {
  padding-left: 20px;
  font-weight: bold;

  &::before {
    border-left: unset;
  }
  &::after {
    border-top: unset;
  }
  > .el-tree-node__children {
    display: flex;
    flex-wrap: wrap;
    padding: 5px;

    ::v-deep.el-tree-node__label {
      font-weight: normal;
    }
  }
}
.avater {
  height: 50px;
  width: 50px;
  border-radius: 50%;

  margin: 10px;
  &:hover {
    box-shadow: 2px 2px 5px #ccc;
    cursor: pointer;
  }
}
.el-checkbox-group {
  margin-left: 15px;
  label {
    position: relative;
    float: left;
  }
}
</style>
